package com.jiangyg.mall.core.support.validation.constraints;

import com.jiangyg.mall.core.support.validation.AbstractConstraintValidator;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 类描述：邮箱格式校验
 *
 * @author jiangyg
 * @version 2.0
 * @date 2020-08-02
 */
@Documented
@Retention(RUNTIME)
@Constraint(validatedBy = {Email.EmailConstraintValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
public @interface Email {

    String message() default "{custom.validation.constraints.Email.message}";

    String regexp() default "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 类描述：手机号码校验执行器
     *
     * @author jiangyg
     * @version 2.0
     * @date 2020-08-02
     */
    class EmailConstraintValidator extends AbstractConstraintValidator<Email, String> {

        @Override
        public boolean execute(Email a, String value, ConstraintValidatorContextImpl contextImpl) {
            // 非必填则可为空
            if (StringUtils.isBlank(value)) {
                return true;
            }
            // 匹配正则
            return Pattern.matches(a.regexp(), value);
        }

    }

}
